<template>
  <div class="dashboard-container">
    <div class="container">
      <div class="tableBar">
        <label style="margin:0 5px 0 15px">桌号：</label>
        <el-input
          v-model="place"
          placeholder="请输桌号"
          style="width: 8%"
          clearable
          @clear="init"
          @keyup.enter.native="initFun"
        />
        <el-button type="primary" style="margin: 0 20px" @click="dialogPlaceShow">
          查看&结账
        </el-button>

        <label style="margin:0 5px">流水单号：</label>
        <el-input
          v-model="number"
          placeholder="请输入流水单号"
          style="width: 15%"
          clearable
          @clear="init"
          @keyup.enter.native="initFun"
        />
        <el-button class="normal-btn continue" @click="init(true)">
          查询
        </el-button>
        <div style="display: flex;justify-content:end;align-items: center;width:auto;gap: 10px;float:right">
          <el-input v-model="fromPlace" placeholder="桌号" style="width: 14%" clearable @clear="place1=''"/>
          <img class="go" src="@/icons/svg/go.svg"
               style="width: 25px;height:30%;border-radius:50%;background-color: #efb602" fit="fill" alt=""
          >
          <el-input v-model="toPlace" placeholder="桌号" style="width: 14%" clearable @clear="place2=''"/>
          <el-button
            type="primary"
            style="float: right"
            @click="onChangePlace"
          >
            换桌
          </el-button>
        </div>
      </div>
      <el-table
        v-if="tableData.length"
        :data="tableData"
        stripe
        class="tableBox"
      >
        <el-table-column prop="number" label="流水单号"/>
        <el-table-column prop="place" label="桌号" width="80px" align="center">
          <template v-slot="{ row }">
            <el-button
              type="text"
              size="small"
              style="color: #000;padding: 10px;font-size: 16px;font-weight: 900"

              @click="place=row.place;row.status===2?(toPlace=row.place):(fromPlace=row.place)"
            >
              {{ row.place }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template v-slot="{ row }">
            <span :style="{backgroundColor: statusList[row.status].color,padding:'4px 9px',borderRadius:'5px'}"
                  @click="place=row.place;row.status===2?(toPlace=row.place):(fromPlace=row.place)"
            >{{ statusList[row.status].label }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="people" label="人数" width="80px" align="center"/>
        <el-table-column prop="amount" label="应收金额" align="right"/>
        <el-table-column prop="payAmount" label="实收金额" align="right"/>
        <el-table-column prop="createTime" label="创建时间" align="center"/>
        <el-table-column prop="completeTime" label="最后操作时间" align="center"/>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip/>
        <el-table-column label="操作" width="200" header-align="center" align="right">
          <template v-slot="{row}">
            <!--            <el-button-->
            <!--              type="text"-->
            <!--              size="small"-->
            <!--              class="blueBug"-->
            <!--              @click="addEmployeeHandle(scope.row.id, scope.row.username)"-->
            <!--            >-->
            <!--              修改-->
            <!--            </el-button>-->
            <el-button
              v-if="row.status !== 2"
              type="text"
              size="small"
              class="delBut"
              @click="cleanPlaceHandle(row)"
            >
              清台
            </el-button>
            <el-button
              type="text"
              size="small"
              class="blueBug"
              @click="showDetailHandle(row)"
            >
              {{ row.status === 2 ? '查看' : '结账' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Empty v-else :is-search="isSearch"/>
      <el-pagination
        class="pageList"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="counts"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :title="place?`${place}号桌-订单信息`:'订单信息'"
      :visible.sync="dialogPlaceVisible"
      width="53%"
      center
      class="order-dialog"
    >
      <el-scrollbar style="height: 100%">
        <div>
          <div v-for="orderPlace in orderByPlaceList" :key="orderPlace.id">
            <order-detail :dia-form="orderPlace"
                          @updateOrderDetailData="getOrderByPlaceList"
                          @updateOrderListData="init"
            />
          </div>
        </div>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <el-row style="width: 100%">
          <el-col :span="10" style="display: flex;justify-content: start;margin-left: 80px">
            <span style="font-size: 17px">合计：{{ totalAmount }}</span>
          </el-col>
          <el-col :span="10" style="display: flex;justify-content: end;margin-right: 50px">
            <el-button
              @click="handleClose"
            >返 回</el-button>
            <el-button
              type="primary"
              @click="getDetailHandle"
            >生成账单</el-button>
          </el-col>
        </el-row></span>
    </el-dialog>

    <!--    <el-dialog-->
    <!--      title="结账"-->
    <!--      :visible.sync="dialogSubmitVisible"-->
    <!--      width="40%"-->
    <!--      :before-close="handleCloseSubmit"-->
    <!--      class="order-dialog"-->
    <!--    >-->
    <!--      <el-form-->
    <!--        ref="statementSubmitForm"-->
    <!--        :model="statementSubmitForm"-->
    <!--        :rules="rules"-->
    <!--        label-width="120px"-->
    <!--        style="width: 70%"-->
    <!--      >-->
    <!--        <el-form-item label="桌号：">-->
    <!--          <span style="font-size: 17px">{{ place }}</span>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="支付方式：">-->
    <!--          <el-select-->
    <!--            v-model="statementSubmitForm.payMethod"-->
    <!--            placeholder="请选择"-->
    <!--            style="width: 100%"-->
    <!--          >-->
    <!--            <el-option-->
    <!--              v-for="item in payMethodList"-->
    <!--              :key="item.value"-->
    <!--              :label="item.label"-->
    <!--              :value="item.value"-->
    <!--            />-->
    <!--          </el-select>-->
    <!--        </el-form-item>-->

    <!--        <el-form-item label="应收金额：">-->
    <!--          <span style="font-size: 16px;color: red">￥{{ totalAmount.toFixed(2) }}</span>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="实收金额：" prop="payAmount">-->
    <!--          <el-input v-model="statementSubmitForm.payAmount" type="number" style="width: 100%"/>-->
    <!--        </el-form-item>-->
    <!--        <el-form-item label="备注：" prop="remark">-->
    <!--          <el-input v-model="statementSubmitForm.remark" type="textarea" style="width: 100%"/>-->
    <!--        </el-form-item>-->
    <!--      </el-form>-->
    <!--      <span slot="footer" class="dialog-footer">-->
    <!--        <el-button @click="handleCloseSubmit">返 回</el-button>-->
    <!--        <el-button type="primary" @click="onSubmit">确 定</el-button>-->
    <!--      </span>-->
    <!--    </el-dialog>-->
    <el-dialog
      :title="!isView?'待提交结算单':statementsWithDetails.length===1?'查看结算单':'查看结算单 （'+(currentStatementIndex+1)+'/'+statementsWithDetails.length+'）'"
      :visible.sync="dialogStatementVisible"
      width="40%"
      center
      :before-close="handleCloseStatement"
      class="order-dialog"
    >
      <el-scrollbar style="height: 100%">
        <div style="padding: 20px">
          <div style="width: 100%;margin-bottom: 30px">
            <span style="font-size: 17px;padding-left: 30px">{{
                place
              }}号桌 - 结算单{{
                isView&&statementsWithDetails.length>0 ? `号:${statementsWithDetails[currentStatementIndex].number}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;结算时间： ${statementsWithDetails[currentStatementIndex].createTime}` : ''
              }}</span>
          </div>
          <div>
            <el-table :data="statementDetailList" style="width: 100%">
              <el-table-column prop="name" label="名称" width="180">
                <template v-slot="{row}">
                  <span>{{ row.id ? row.name : '**' + row.name }}</span>
                </template>
              </el-table-column>
              <el-table-column prop="number" label="数量" width="80"/>
              <el-table-column prop="amount" label="单价"/>
            </el-table>
          </div>
          <div v-if="isAddDetail">
            <el-row
              style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: start;margin-top: 20px;column-gap: 2px"
            >
              <el-col :span="6">
                <el-input v-model="addDetailForm.name" placeholder="名称"/>
              </el-col>
              <el-col :span="3">
                <el-input v-model="addDetailForm.number" type="number" placeholder="数量" input-align="center"/>
              </el-col>
              <el-col :span="4">
                <el-input v-model="addDetailForm.amount" type="number" placeholder="单价" class="input-add-detail"/>
              </el-col>
              <el-col :span="5" style="height: 100%;display: flex;align-items: center;justify-content: end">
                <span>实收金额调整为：</span>
              </el-col>
              <el-col :span="4">
                <el-input v-model="updatePayAmount" type="number" placeholder="实收金额"/>
              </el-col>
              <el-col :span="2">
                <el-button type="primary" size="small" @click="AddDetailhandle">
                  完成
                </el-button>
              </el-col>
            </el-row>
          </div>
          <div style="display: flex;flex-direction: column;gap: 10px;padding-left: 30px;margin-top: 20px">
            <span style="margin-bottom: 10px">应收金额：<span style="font-size: 12px;color: red">￥</span><span
              style="color: red;font-size: 18px"
            >{{ dialogStatement.amount }}</span></span>
            <span style="margin-bottom: 10px">实收金额：<span style="font-size: 12px;color: red">￥</span><span
              style="color: red;font-size: 18px"
            >{{ dialogStatement.payAmount }}</span></span>
            <div>
              <span style="margin-top:10px">支付方式：</span>
              <el-radio-group v-model="dialogStatement.payMethod" size="small">
                <el-radio-button
                  v-for="item in payMethodList"
                  :key="item.value"
                  :label="item.value"
                >
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </div>
            <span style="margin-top:10px">备注：</span>
            <el-input v-model="dialogStatement.remark" type="textarea" style="width: 100%"/>
            <span style="margin-top:10px">说明：名称前面带**的是调整项，每个结算单只能有一个调整项</span>
          </div>
        </div>
      </el-scrollbar>

      <span slot="footer" class="dialog-footer">
        <el-button v-if="isView&&statementsWithDetails.length>1" :disabled="currentStatementIndex===0"
                   @click="currentStatementIndex--;getStatementDetailList()"
        >上一页</el-button>
        <el-button v-if="isView&&statementsWithDetails.length>1"
                   :disabled="currentStatementIndex===statementsWithDetails.length-1" style="margin-right: 80px"
                   @click="currentStatementIndex++;getStatementDetailList()"
        >下一页</el-button>
        <el-button @click="handleCloseStatement">返 回</el-button>
        <el-button type="info" @click="OnAddDetail">调 整</el-button>
        <el-button type="primary" @click="onSubmit">{{ isView ? '修改&打印' : '提交&打印' }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {Component, Vue} from 'vue-property-decorator'
import Empty from '@/components/Empty/index.vue'
import {
  getAdminStatementListApi,
  getTurnoverPageApi,
  postStatementSubmitApi,
  putAdminTurnoverChangePlaceApi,
  putAdminTurnoverUpdateApi,
  putStatementUpdateApi,
} from '../../api/statement';
import OrderDetail from '@/components/order/OrderDetail.vue'
import {getOrderPlaceApi} from '../../api/order'; // getOrderPlaceApi
import {reduceList} from '../../utils/common';

// noinspection TypeScriptValidateTypes
@Component({
  name: 'Employee',
  components: {
    Empty,
    OrderDetail,
  },
})
export default class extends Vue {
  private number: any = ''
  private place: any = ''
  private fromPlace: any = ''
  private toPlace: any = ''
  private counts: number = 0
  private page: number = 1
  private pageSize: number = 10
  private tableData = []
  private isSearch: boolean = false
  private dialogPlaceVisible = false
  private orderByPlaceList = []
  private dialogStatementVisible = false
  private dialogStatement = {payMethod: 1, remark: ''} as any
  private statementDetailList = []
  private isAddDetail = false
  private updatePayAmount = 0
  private addDetailForm = {
    name: '',
    number: '',
    amount: '',
  }
  private statementSubmitForm = {
    id: undefined,
    number: '',
    turnoverId: undefined,
    payMethod: 1,
    amount: 0,
    payAmount: 0,
    remark: '',
    orderIds: [],
  }
  private payMethodList = [
    {
      value: 1,
      label: '微信',
    },
    {
      value: 2,
      label: '支付宝',
    },
    {
      value: 3,
      label: '现金',
    },
    {
      value: 4,
      label: 'POS机',
    },
    {
      value: 5,
      label: '闪付',
    },
    {
      value: 6,
      label: '其他',
    }
  ]
  private statusList = [
    {
      value: 0,
      label: '未结账',
      color: '#1bd1a5',
    },
    {
      value: 1,
      label: '未清台',
      color: '#d3d4cc',
    },
    {
      value: 2,
      label: '已完成',
      color: '',
    }
  ]
  private isView = false
  private statementsWithDetails = []
  private title = ''
  private currentStatementIndex = 0;

  created() {
    this.init()
  }

  initFun() {
    this.page = 1
    this.init()
  }

  private async init(isSearch?: boolean) {
    this.isSearch = isSearch
    const params = {
      page: this.page,
      pageSize: this.pageSize,
      number: this.number ? this.number : undefined,
      place: this.place ? this.place : undefined,
    }
    await getTurnoverPageApi(params)
      .then((res: any) => {
        console.log(res.data)
        if (res.data.code === 1) {
          this.tableData = res.data && res.data.data && res.data.data.records
          for (let item of this.tableData) {
            if (item.remark){
              const remark = item.remark.split('^')
              for (let i = 0; i < remark.length; i++) {
                const index = remark[i].indexOf(',调整：')
                if (index !== -1) {
                  remark[i] = remark[i].slice(0, index)
                }
              }
              item.remark =remark.filter((item) => item && item.trim()).join(';')
            }
          }
          this.counts = res.data.data.total
        }
      })
      .catch((err) => {
        this.$message.error('请求出错了：' + err.message)
      })
  }

  handleSizeChange(val: any) {
    this.pageSize = val
    this.init()
  }

  handleCurrentChange(val: any) {
    this.page = val
    this.init()
  }

  // 点击查看&结账时触发
  async dialogPlaceShow(place = null) {
    await this.getOrderByPlaceList(place)
    if (this.orderByPlaceList && this.orderByPlaceList.length > 0) {
      this.dialogPlaceVisible = true
    }
  }

  // 获取该桌未结账订单列表
  async getOrderByPlaceList(place = null) {
    if (place && (typeof place === 'string' || typeof place === 'number')) {
      this.place = place
    }
    if (!this.place) {
      return
    }
    const res = await getOrderPlaceApi(this.place)
    this.orderByPlaceList = res.data.data || []
    if (res.data.data && res.data.data.length == 0) {
      this.$message.error('该桌暂无未结账订单')
    }
  }

  initProp() {
    this.statementSubmitForm = {
      id: undefined,
      number: '',
      turnoverId: undefined,
      payMethod: 1,
      amount: 0,
      payAmount: 0,
      remark: '',
      orderIds: [],
    }
    this.orderByPlaceList = []
    this.statementsWithDetails = []
  }

  handleClose() {
    this.dialogPlaceVisible = false
    this.initProp()
  }

  get totalAmount() {
    return this.orderByPlaceList.reduce((acc, item) => acc + item.amount, 0)
  }

  get statementTotalAmount() {
    return this.statementDetailList.reduce((acc, item) => acc + item.amount * item.number, 0)
  }

  // 点击生成订单触发
  getDetailHandle(row) {
    let hasOrder = false
    for (let order of this.orderByPlaceList) {
      if (order.status < 3) {
        this.$message.error('订单中有未完成项，请先处理订单')
        return
      }
      if (order.status == 3) {
        hasOrder = true
      }
    }
    if (!hasOrder) {
      this.$message.error('该桌暂无未结账订单')
      return
    }
    this.statementDetailList = []
    this.orderByPlaceList.forEach(item => {
      this.statementDetailList.splice(this.statementDetailList.length, 0, ...item.orderDetailList)
    })
    this.statementDetailList = reduceList(this.statementDetailList)

    this.dialogStatement.amount = this.dialogStatement.payAmount = this.statementTotalAmount
    this.dialogPlaceVisible = false
    this.dialogStatementVisible = true
    console.log('this.statementDetailList: ', this.statementDetailList)
  }

  // 点击调整触发
  OnAddDetail() {
    console.log('OnAddDetail', this.dialogStatement)
    if (this.statementDetailList[this.statementDetailList.length - 1].id === 0) {
      const detail = this.statementDetailList.pop()
      this.addDetailForm = {
        name: detail.name,
        number: detail.number,
        amount: detail.amount,
      }
    } else {
      this.addDetailForm = {
        name: '退货',
        number: '-1',
        amount: '',
      }
    }
    this.isAddDetail = true
  }

  // 点击调整行输入完成时触发
  AddDetailhandle() {
    this.addDetailForm.name=this.addDetailForm.name.trim()
    if (!this.addDetailForm.name){
      this.$message.error('名称不能为空')
      return;
    }
    if (isNaN(Number(this.addDetailForm.number)) || isNaN(Number(this.addDetailForm.amount))) {
      this.$message.error('数量或金额有误，请输入正确的数字')
      return
    }
    this.isAddDetail = false
    if (Number(this.addDetailForm.number) !== 0 && Number(this.addDetailForm.amount) !== 0) {
      this.statementDetailList.push({
        name: this.addDetailForm.name,
        number: this.addDetailForm.number,
        amount: this.addDetailForm.amount,
        id: 0
      })
    }
    this.dialogStatement.amount = this.statementTotalAmount
    this.dialogStatement.payAmount = this.updatePayAmount || this.statementTotalAmount
  }

  // 点击提交&打印时触发
  async onSubmit() {
    if (this.isAddDetail) {
      this.$message.error('请先完成调整')
      return
    }
    if (this.dialogStatement.remark && this.dialogStatement.remark.length > 150) {
      this.$message.error('备注长度不能超过150个字符')
      return
    }
    if (!this.isView) {
      this.statementSubmitForm.orderIds = this.orderByPlaceList.map((item) => item.id)
      this.statementSubmitForm.number = Date.now() + '-' + Math.random().toString(36).slice(2, 4).toUpperCase()
      this.statementSubmitForm.turnoverId = this.orderByPlaceList[0].turnoverId
    }else {
      this.statementSubmitForm.id = this.dialogStatement.id
    }
    this.statementSubmitForm.payMethod = this.dialogStatement.payMethod || 1
    this.statementSubmitForm.amount = this.statementTotalAmount
    this.statementSubmitForm.payAmount = this.dialogStatement.payAmount
    if (this.statementDetailList[this.statementDetailList.length - 1].id === 0) {
      this.dialogStatement.remark = this.dialogStatement.remark + ',调整：' + this.addDetailForm.name + '*' + this.addDetailForm.number + '*' + this.addDetailForm.amount
    }
    this.statementSubmitForm.remark = this.dialogStatement.remark || null
    console.log('this.statementSubmitForm', this.statementSubmitForm)
    await this.$confirm('确定要提交吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '再想想',
      type: 'warning',
    })
    console.log('点确认了')
    if (!this.isView) {
      await postStatementSubmitApi(this.statementSubmitForm)
    } else {
      await putStatementUpdateApi(this.statementSubmitForm)
    }
    this.$message({
      type: 'success',
      message: '提交成功!',
    })
    this.dialogStatementVisible = false
    this.fromPlace = this.toPlace = this.place = null
    this.handleCloseStatement()
    this.init()
  }

  // 点击换桌触发(修改完成）
  async onChangePlace() {
    if (!this.fromPlace || !this.toPlace) {
      this.$message.error('请输入原桌号和目标桌号')
      return
    }
    if (this.fromPlace === this.toPlace) {
      this.$message.error('原桌号和目标桌号不能相同')
      return
    }
    if (isNaN(Number(this.fromPlace)) || isNaN(Number(this.toPlace))) {
      this.$message.error('请输入正确的桌号')
      return
    }
    await this.$confirm(`确定要把 ${this.fromPlace} 号桌调换到 ${this.toPlace} 号桌吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    await putAdminTurnoverChangePlaceApi({fromPlace: this.fromPlace, toPlace: this.toPlace})
    this.$message.success('换桌完成')
    this.fromPlace = this.toPlace = this.place = null
    this.init()
  }

  handleCloseStatement() {
    this.isView=false
    this.isAddDetail = false
    this.updatePayAmount = 0
    this.addDetailForm = {
      name: '',
      number: '',
      amount: '',
    }
    this.dialogStatement = {
      payMethod: 1,
      remark: '',
    }
    this.dialogStatementVisible = false
    this.initProp()
  }

  // 点击清台触发
  cleanPlaceHandle(row) {
    this.$confirm(`确定 ${row.place} 号桌客人已经离开，需要清台吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '再等等',
      type: 'warning',
    })
      .then(() => {
        putAdminTurnoverUpdateApi({
          id: row.id,
          status: 2,
        })
          .then((res) => {
            if (res.data.code === 1) {
              this.$message({
                type: 'success',
                message: '清台成功!',
              })
              this.fromPlace = this.toPlace = this.place = null
              this.init()
            }
          })
      })
  }

  async getStatementListByTurnoverId(id) {
    const res = await getAdminStatementListApi({
      turnoverId: id,
    })
    this.statementsWithDetails = res.data.data || []
  }

  // 点击结账、查看触发
  async showDetailHandle(row) {
    this.place = row.place
    if (row.status === 2) {
      await this.getStatementListByTurnoverId(row.id)
      if (this.statementsWithDetails.length === 0) {
        return
      }
      this.getStatementDetailList()
      this.isView = true
      this.dialogStatementVisible = true
    } else {
      this.dialogPlaceShow(row.place)
    }
  }

  getStatementDetailList() {
    const statement = this.statementsWithDetails[this.currentStatementIndex]
    console.log('statement', statement)
    this.statementDetailList = [...statement.orderDetails]
    this.dialogStatement.id=statement.id
    this.dialogStatement.remark = statement.remark||''
    this.dialogStatement.payMethod = statement.payMethod
    const index = this.dialogStatement.remark.indexOf(',调整：')
    if (index !== -1) {
      const remark = this.dialogStatement.remark.slice(index + ',调整：'.length).split('*')
      this.dialogStatement.remark = this.dialogStatement.remark.slice(0, index)
      this.statementDetailList.push({
        id: 0,
        name: remark[0],
        number: remark[1],
        amount: remark[2],
      })
    }
    this.dialogStatement.payAmount = statement.payAmount
    this.dialogStatement.amount = statement.amount
  }

}

</script>

<style lang="scss" scoped>
.disabled-text {
  color: #bac0cd !important;
}

.order-dialog {
  //text-align: center;
}

</style>
